package com.wolf.etl.core;

import com.wolf.etl.core.loadbalance.LoadBalanceManage;
import com.wolf.etl.core.task.ScheduleJobService;
import com.wolf.etl.core.task.TaskStatus;
import com.wolf.etl.enumeration.INSTANCE_STATUS;
import com.wolf.etl.model.EtlInstanceModel;
import com.wolf.etl.model.EtlTaskModel;
import com.wolf.etl.vo.ServiceInfo;
import com.wolf.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author sdyang
 * @date 2019/10/12 10:51
 **/
@Component
@Order(1)
public class InitService implements ApplicationRunner {

    private static Logger logger = LoggerFactory.getLogger(InitService.class);

    private static final String logger_prefix = "wolf-etl#com.wolf.etl.core#InitService";

    private ServiceInfo serviceInfo;


    @Value("${server.port}")
    private Integer port;
    @Autowired
    private ETLManager etlManager;
    @Autowired
    private LoadBalanceManage loadBalanceManage;
    @Autowired
    private ScheduleJobService scheduleJobService;

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {

        // 读取服务器信息
        readServerInfo();

        // 初始化实例信息
        initInstances();

        // 初始化分布式策略
        loadBalanceManage.init(etlManager);

        // 启动定时任务
        scheduleJobService.init();
    }

    private void initInstances() {

        List<EtlTaskModel> tasks = etlManager.findTaskByStatus(TaskStatus.ENABLE);
        for (EtlTaskModel task : tasks) {
            EtlInstanceModel instance = etlManager.findInstance(task.getId(), serviceInfo.getInstance_id());

            // 不为空，跳过
            if (instance != null) {
                continue;
            }
            instance = new EtlInstanceModel();
            instance.setCode(serviceInfo.getInstance_id());
            instance.setTask_id(task.getId());
            instance.setIp(IPUtil.getLocalIP());
            instance.setMac_address(MacUtil.getMACAddress());
            instance.setStatus(INSTANCE_STATUS.ENABLE.getValue());
            instance.setPort(port);

            etlManager.insertInstance(instance);
        }
    }

    private void readServerInfo() {
        serviceInfo = new ServiceInfo();
        serviceInfo.setIp(IPUtil.getLocalIP());
        serviceInfo.setHostname(IPUtil.getHostName());
        Map<String, String> data = PropertiesUtil.read("init.properties");
        String instance_id = "";
        Integer weight = 0;

        // 没有配置文件
        if (data == null || data.size() == 0) {
            FileUtil.create("init.properties");
        }

        // 没有实例编码
        if(StringUtils.isEmpty(data.get("instance_id"))){
            instance_id = UUID.randomUUID().toString();
            PropertiesUtil.update("init.properties", "instance_id", instance_id);
        }else{
            instance_id = data.get("instance_id");
        }

        //权重
        weight = data.get("weight") == null ? 0 : Integer.parseInt(data.get("weight"));

        serviceInfo.setInstance_id(instance_id);
        serviceInfo.setWeight(weight);
    }

    public ServiceInfo getServiceInfo() {
        return serviceInfo;
    }

    public void setServiceInfo(ServiceInfo serviceInfo) {
        this.serviceInfo = serviceInfo;
    }

    public String getInstanceCode() {
        return serviceInfo.getInstance_id();
    }

    private Integer getWeight() {
        return serviceInfo.getWeight();
    }

}
